"""
封装 Coze API 调用为函数，输入文本返回响应结果
"""
import json
from cozepy import COZE_CN_BASE_URL
from cozepy import Coze, TokenAuth, Stream, WorkflowEvent, WorkflowEventType

# 全局配置
coze_api_token = 'pat_bkJmbt7cBmrNf8PeoRA4GjzIn3h9PJofkuCP5Wg9rfxXiwuc8C8WFRrplWt2cqVv'
coze_api_base = COZE_CN_BASE_URL
workflow_id = '7569130821820809252'

# 初始化 Coze 客户端
coze = Coze(auth=TokenAuth(token=coze_api_token), base_url=coze_api_base)

def chat_with_coze(text: str) -> str:
    """
    向 Coze 工作流发送文本并返回响应结果
    
    Args:
        text (str): 要发送的文本内容
        
    Returns:
        str: Coze 工作流的响应内容
    """
    # 定义输入参数
    input_params = {
        "input": text  # 键必须匹配工作流定义的输入参数名
    }
    
    # 收集所有消息内容
    responses = []
    
    def handle_workflow_stream(stream: Stream[WorkflowEvent]):
        """处理工作流事件流"""
        for event in stream:
            if event.event == WorkflowEventType.MESSAGE:
                # 收集消息内容
                if hasattr(event, 'message') and hasattr(event.message, 'content'):
                    responses.append(event.message.content)
            elif event.event == WorkflowEventType.ERROR:
                error_msg = f"错误: {event.error.message}" if hasattr(event, 'error') else "未知错误"
                responses.append(error_msg)
            elif event.event == WorkflowEventType.INTERRUPT:
                # 处理中断事件
                handle_workflow_stream(
                    coze.workflows.runs.resume(
                        workflow_id=workflow_id,
                        event_id=event.interrupt.interrupt_data.event_id,
                        resume_data="继续",
                        interrupt_type=event.interrupt.interrupt_data.type,
                    )
                )
    
    # 执行工作流
    handle_workflow_stream(
        coze.workflows.runs.stream(
            workflow_id=workflow_id,
            parameters=input_params
        )
    )
    
    # 返回所有消息的合并结果
    return json.loads(''.join(responses) if responses else "未收到响应")

# 使用示例
if __name__ == "__main__":
    # 测试函数
    test_text = "KY-BA1037A-9015-SHUIXILAN-S"
    result = chat_with_coze(test_text)
    print("Coze 响应:")
    print(result['output'])